<template>
  <div id="loginContainer">
    <HeaderTop ref="header" :title="header.title" :bg="header.bg" :color="header.color">
      <router-link to="/" class="header_left" slot="left">
        <i class="iconfont icon-arrow-left"></i>
      </router-link>
      <router-link to="" class="header_right" slot="right">
        <i class="iconfont icon-three-dot"></i>
      </router-link>
    </HeaderTop>
    <section class="main">
      <form @submit.prevent="login" autocomplete="off">
        <section v-if="loginWay">
          <div class="input-container phone">
            <input type="text"
                   placeholder="请输入手机号"
                   maxlength="11"
                   v-model="phone"
                   @focus="toggleError('phone')"
                   @blur="toggleError('phone')">
            <i class="iconfont icon-error" v-if="error.phone" @click="clearText('phone')"></i>
            <button class="get-verification"
                    :disabled="!rightPhone"
                    :class="{right_phone: rightPhone}"
            @click.prevent="getCode">
              {{ computeTime > 0 ? `${computeTime}s` : '获取验证码' }}
            </button>
          </div>
          <div class="input-container code">
            <input type="text"
                   placeholder="请输入收到的短信验证码"
                   maxlength="6"
                   v-model="code"
                   @focus="toggleError('code')"
                   @blur="toggleError('code')">
            <i class="iconfont icon-error" v-if="error.code" @click="clearText('code')"></i>
          </div>
          <button class="login-submit">登录</button>
          <div class="pwd-login">
            <span @click="toggleType()">账号密码登录</span>
          </div>
        </section>
        <section v-else="!loginWay">
          <div class="input-container username">
            <input type="text"
                   placeholder="用户名/邮箱/已验证手机"
                   v-model="username"
                   @focus="toggleError('name')"
                   @blur="toggleError('name')">
            <i class="iconfont icon-error" v-if="error.name" @click="clearText('username')"></i>
          </div>
          <div class="input-container password">
            <input :type="!isShowPwd ? 'password' : 'text' " placeholder="请输入密码"
                   autocomplete="off"
                   v-model="password"
                   @focus="toggleError('password')"
                   @blur="toggleError('password')">
            <i class="iconfont icon-error" @click="clearText('password')"  v-if="error.password"></i>
            <div class="eyes" @click="toggleShowPwd">
              <img src="./images/hidePwd_icon.png" v-if="!isShowPwd">
              <img src="./images/showPwd_icon.png" v-else="isShowPwd">
            </div>
          </div>
          <div class="input-container captcha">
            <input type="text"
                   placeholder="验证码"
                   autocomplete="off"
                   v-model="captcha"
                   @focus="toggleError('captcha')"
                   @blur="toggleError('captcha')"
                   maxlength="4">
            <i class="iconfont icon-error" v-if="error.captcha" @click="clearText('captcha')"></i>
            <img class="captchaImg" src="http://localhost:8001/captcha" @click="getCaptcha" ref="captcha">
          </div>
          <button class="login-submit">登录</button>
          <div class="sms_login">
            <span @click="toggleType()">短信验证码登录</span>
          </div>
        </section>
      </form>
    </section>
    <AlertTip :alertText="alertText" v-show="alertShow" @closeTip="closeTip" />
  </div>
</template>

<script>
  import HeaderTop from '../../components/HeaderTop/HeaderTop'
  import AlertTip from '../../components/AlertTip/AlertTip'
  import {
    reqSendCode, // 获取短信验证码
    reqSmsLogin, // 短信登录
    reqPwdLogin // 账号密码登录
  }  from '../../api'

  export default {
    data () {
      return {
        header: {
          title: '京东登录',
          iconLeft: 'icon-arrow-left',
          color: '#666'
        },
        loginWay: true, // true: 短信登录, false: 账号密码登录
        computeTime: 0, // 计时的时间
        isShowPwd: false, // 是否显示密码
        username: '', // 用户名
        password: '', // 密码
        phone: '', // 手机号
        code: '', // 短信验证码
        captcha: '', // 图形验证码
        alertText: '提示文本',
        alertShow: false, // 是否显示提示框
        error: {
          name: false,
          password: false,
          captcha: false,
          phone: false,
          code: false
        }
      }
    },
    computed: {
      rightPhone () {
        return /^1\d{10}$/.test(this.phone)
      }
    },
    methods: {
      // 切换隐藏显示密码
      toggleShowPwd () {
        this.isShowPwd = !this.isShowPwd
      },
      // 点击清除号, 清除对应的input值
      clearText (type) {
        if (type === 'username') {
          this.username = ''
        } else if (type === 'password') {
          this.password = ''
        } else if (type === 'captcha') {
          this.captcha = ''
        } else if (type === 'code') {
          this.code = ''
        } else if (type === 'phone') {
          this.phone = ''
        }
      },
      // 切换清除号显示隐藏
      toggleError (type) {
        if (type === 'name') {
          this.clearError('name')
        } else if (type === 'password') {
          this.clearError('password')
        } else if (type === 'captcha') {
          this.clearError('captcha')
        } else if (type === 'phone') {
          this.clearError('phone')
        } else if (type === 'code') {
          this.clearError('code')
        }
      },
      clearError (type) {
        setTimeout(() => {
          this.error[type] = !this.error[type]
        }, 200)
      },
      // 异步获取短信验证码
      async getCode () {
        // 如果当前没有计时
        if (!this.computeTime) {
          // 启动定时器
          this.computeTime = 60
          this.timeId = setInterval(() => {
            this.computeTime--
            if (this.computeTime <= 0) {
              clearInterval(this.timeId)
            }
          }, 1000)

          // 发送 ajax 请求(向指定手机号发送验证码)
          console.log(this.phone);
          const result = await reqSendCode(this.phone)
          console.log(result)
          if (result.code === 1) {
            // 显示提示
            this.showAlert(result.msg)
            // 停止倒计时
            if (this.computeTime) {
              this.computeTime = 0
              clearInterval(this.timeId)
              this.timeId = undefined
            }
          }
        }
      },
      // 提示框
      showAlert (alertText) {
        this.alertShow = true
        this.alertText = alertText
      },
      // 登录功能
      async login () {
        let result
        // 前台表单提交
        if (this.loginWay) { // 短信登录
          const { rightPhone, phone, code } = this
          if (!rightPhone) {
            // 手机号不正确
            return this.showAlert('手机号不正确')
          } else if (!/^\d{6}$/.test(code)) {
            // 验证码必须是6位数字
            return this.showAlert('验证码必须是6位数字')
          }
          // 发送 ajax 请求短信登录
          result = await reqSmsLogin({ phone, code })
        } else { // 账号密码登录
          const { username, password, captcha } = this
          console.log(username, password, captcha)
          if (!username) {
            // 用户名必须指定
            return this.showAlert('用户名必须指定')
          } else if (!password) {
            // 密码必须指定
            return this.showAlert('密码必须指定')
          } else if (!captcha) {
            // 验证码必须指定
            return this.showAlert('验证码必须指定')
          }
          // 发送 ajax 请求账号密码登录
          result = await reqPwdLogin({ username, password, captcha })
        }

        // 停止倒计时
        if (this.computeTime) {
          this.computeTime = 0
          clearInterval(this.timeId)
          this.timeId = undefined
        }

        // 根据结果数据处理
        if (result.code === 0) {
          // console.log(result)
          // localStorage.setItem('isLogin', true)
          const user = result.data
          // 将 user 保存到 vuex 中的 state
          this.$store.dispatch('recordUser', user)
          // 去个人界面
          this.$router.replace('/profile')
        } else {
          // console.log(result)
          // localStorage.setItem('isLogin', '')
          // 显示新的图片验证码
          this.getCaptcha()
          // 显示警告信息
          const msg = result.msg
          this.showAlert(msg)
        }
      },
      // 获取一个新的图像验证码
      getCaptcha () {
        // 每次指定的 src 都要不是一样
        this.$refs.captcha.src = 'http://localhost:8001/captcha?time=' + Date.now()
      },
      // 切换登录方式
      toggleType () {
        this.loginWay = !this.loginWay
        if (this.loginWay) {
          this.phone = ''
          this.code = ''
          return
        }
        this.username = ''
        this.password = ''
        this.captcha = ''
      },
      // 关闭提示框
      closeTip () {
        this.alertShow = false
        this.alertText = ''
      }
    },
    components: {
      HeaderTop,
      AlertTip
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  @import "../../assets/stylus/mixins.styl"
  #loginContainer
    width: 100%
    margin-top 44px
    color(#fff)
    .main
      padding 25px
      position: relative
      form
        width: 100%
        margin-bottom: 30px
        .input-container
          size(100%, 50px)
          color(#222)
          border-box()
          bottom-border-1px(#efefef)
          padding-top 10px
          padding-bottom 10px
          margin-top 20px
          position relative
          overflow hidden
          &.phone
            .get-verification
              size(100px, 34px)
              center-text()
              fz(14px)
              color(#848689)
              bg(#fff)
              border none
              position absolute
              top 50%
              right 0
              transform translateY(-50%)
              &.right_phone
                color(#fab3b3)
          &.code, &.username, &.password
            .icon-error
              right 36px
          &.captcha
            .captchaImg
              size(100px, 30px)
              position absolute
              right 0
              top 8px
          input
            size(100%, 30px)
            color(#222)
            border-box()
            border none
            line-height 30px
            padding-right 24px
            &:nth-child(2)
              padding-right 65px
          .icon-error
            size(24px, 24px)
            color(#efefef)
            border-box()
            position absolute
            top 50%
            right 120px
            transform translateY(-50%)
            padding 4px
            &.on
              display none
          .eyes
            size(24px, 24px)
            position: absolute;
            right 0
            top 12px
            img
              size(100%, 100%)
        .login-submit
          border 0
          padding 0
          size(100%,50px)
          fz(16px)
          center-text()
          color(#fff)
          display block
          lh(50px)
          background-image linear-gradient(90deg, #fab3b3, #ffbcb3 73%, #ffcaba)
          border-radius 25px
          margin-top 40px
      .sms_login, .pwd-login
        size(100%, 30px)
        fz(14px)
        color(#666)
        lh(30px)
        margin-top 20px
        text-align right
</style>
